package com.falcon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.falcon.core.utils.BeanUtils;
import com.falcon.domain.dos.ApiDO;
import com.falcon.domain.po.ApiPO;
import com.falcon.domain.req.ApiQuery;
import com.falcon.domain.req.ApiRequest;
import com.falcon.mapper.IApiMapper;
import com.falcon.mvc.domain.BasePager;
import com.falcon.service.IApiService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swan.core.utils.TreeUtil;
import com.swan.mybatis.condition.Condition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Slf4j
@Service
public class ApiService implements IApiService {

    @Autowired
    private IApiMapper apiMapper;

    @Override
    public Long save(ApiRequest request){
        ApiPO apiPO = BeanUtil.copyProperties(request, ApiPO.class);

        this.apiMapper.insertNotNull(apiPO);

        return apiPO.getId();
    }

    @Override
    public Boolean update(Long id, ApiRequest request){

        ApiPO apiPO = BeanUtil.copyProperties(request, ApiPO.class);
        apiPO.setId(id);

        return this.apiMapper.updateNotNull(apiPO);
    }

    @Override
    public Boolean deleteById(Long id) {

        return this.apiMapper.deleteById(id);
    }

    @Override
    public ApiDO queryById(Long id){

        ApiPO apiPO = this.apiMapper.selectById(id);

        ApiDO apiDO = BeanUtil.copyProperties(apiPO, ApiDO.class);

        return apiDO;
    }


    @Override
    public List<ApiDO> queryList(ApiQuery request){

        Condition condition = request.toCondition();

        List<ApiPO> poList = this.apiMapper.selectList(condition);

        List<ApiDO> doList = BeanUtil.copyToList(poList, ApiDO.class);

        return doList;
    }

    @Override
    public BasePager<ApiDO> queryPager(ApiQuery request){


        PageInfo<ApiPO> pageInfo = PageHelper.startPage(request.getPage(), request.getPageSize())
                .doSelectPageInfo(() -> this.apiMapper.selectList(request.toCondition()));

        return BeanUtils.toPager(pageInfo, ApiDO.class);
    }

    @Override
    public int batchDelete(List<Long> ids) {

        return this.apiMapper.deleteByIds(ids);
    }

    @Override
    public List<ApiDO> queryTree(ApiQuery request) {

        // 查询所有
        List<ApiDO> list = this.queryList(request);

        // 构建树
        List<ApiDO> treeList =TreeUtil.buildSimpleTree(list, ApiDO::getId, ApiDO::getParentId,0l);

        return treeList;
    }


}

